<?php
/**
 * ws 优化基础类库
 * User: xiant_000
 * Date: 2018/11/11
 * Time: 8:11
 */

class Ws
{
    const HOST = '0.0.0.0';
    const PORT = 8812;

    public $ws = null;
    public function __construct()
    {
        $this->ws = new swoole_websocket_server('0.0.0.0', 8812);

        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('close', [$this, 'onClose']);

        // task
        $this->ws->on('task', [$this, 'onTask']);
        $this->ws->on('finish', [$this, 'onFinish']);

        $this->ws->set([
            'enable_static_handler' => true,
            'document_root' => '/home/work/swoole/data',
            'worker_num'    => '2',
            'task_worker_num'    => '2',
        ]);

        $this->ws->start();
    }

    /**
     * 监听 ws 连接事件
     *
     * @param $ws
     * @param $request
     */
    public function onOpen($ws, $request)
    {
        var_dump($request->fd);
    }

    /**
     * 监听 ws 消息事件
     *
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws, $frame)
    {
        echo 'ser-push-message:' . $frame . "\n";
        // tod 10s
        $data = [
            'task'  => 1,
            'fd'    => $frame->fd,
        ];
        $ws->task($data);
        $ws->push($frame->fd, 'server-push' . date("Y-m-d H:i:s"));
    }

    /**
     * @param $serv
     * @param $taskId
     * @param $workerId
     * @param $data
     * @return string
     */
    public function onTask($serv, $taskId, $workerId, $data)
    {
        print_r($data);
        // 耗时场景 10s
        sleep(10);
        return "on task finish"; // 告诉 worker
    }

    /**
     * @param $serv
     * @param $taskId
     * @param $data
     */
    public function onFinish($serv, $taskId, $data)
    {
        echo 'taskId' . $taskId . PHP_EOL;
        echo 'finish-data-success:' . $data . PHP_EOL;
    }

    /**
     * ws 关闭连接事件
     *
     * @param $ws
     * @param $fd
     */
    public function onClose($ws, $fd)
    {
        echo 'clientId' . $fd . "\n";
    }
}

$obj = new Ws();